package com.erp.erp_project.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.erp_project.core.exception.CustomException;
import com.erp.erp_project.mapper.RoleMapper;
import com.erp.erp_project.mapper.UserMapper;
import com.erp.erp_project.model.Role;
import com.erp.erp_project.model.User;
import com.erp.erp_project.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author yh
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserMapper> implements UserService {

    public UserServiceImpl(UserMapper mapper) {
        super(mapper);
    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User login(String username, String password) throws CustomException {
        User user = userMapper.loginquery(username);

        if (user == null) {
            // 用户不存在
            throw new CustomException("用户不存在");
        }
        if (!SecureUtil.md5(password).equals(user.getPassword())) {
            throw new CustomException("密码不正确");
        }
        // 登录成功
        return user;
    }

    @Override
    public List<User> list(User user,String userfield,String condition) {
            List<User> users=null;
        if (userfield==null||condition==null||condition.trim().equals("")){
            users=userMapper.query(user);
        }
        else if (!userfield.equals("role_name")){
            users=userMapper.requery(userfield,condition);
        }
        else if (userfield.equals("role_name")){
            List<Integer> roleIds=roleMapper.requery(condition);
            List<Integer> userIds=roleMapper.queryur(roleIds);
            users=userMapper.querys(userIds);
        }
        return users;
    }

    @Override
    public User selectuser(User user){
        return userMapper.selectuser(user);
    }

    @Override
    public void delete(List userIds){
        List uids=new ArrayList(userIds);
        List<Integer> ids=roleMapper.queryadmin();
        Iterator it=uids.iterator();
        while (it.hasNext()){
            Integer x=Integer.parseInt((String)it.next());
            if(ids.contains(x)){
                it.remove();
            }
        }
        if(uids.size()!=0){
            userMapper.delete(uids);
            roleMapper.deleteur(uids);
        }
    }

    @Override
    public User updatequery(User user){
        return userMapper.updatequery(user);
    }

}
